package com.accessibleworlds.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

import com.accessibleworlds.R;

public class TextToSpeechesGoogle extends TextToSpeeches{

	private MediaPlayer play;
	
	private boolean loading = true;
	
	@Override
	public void speak(Context context, String data) {
		try {
			if(play != null) {
				if(play.isPlaying()) {
					play.stop();
				}
			}
			
			File file = new File(SharedVariables.folderName+File.separator+data+".mp3");
			if(file.exists()) {
				play = MediaPlayer.create(context, Uri.fromFile(file));
				play.start();
				loading = false;
			}
			else {
				StringBuilder uri = new StringBuilder("");
				uri.append("http://translate.google.com.tr/translate_tts?ie=UTF-8&tl=");
				uri.append(context.getResources().getStringArray(R.array.languagesIDs)[SharedVariables.currentLanguage]);
				uri.append("&q=");
				uri.append(URLEncoder.encode(data, "UTF-8"));
				
				HttpParams params = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(params, 5000);
				HttpConnectionParams.setSoTimeout(params, 5000);
				HttpClient client = new DefaultHttpClient(params);
				
				HttpPost post = new HttpPost(uri.toString());
				HttpResponse response = client.execute(post);
				
				InputStream stream = response.getEntity().getContent();
				int downloadingMediaLength = (int) response.getEntity().getContentLength();
				
				byte dataBytes[] = new byte[downloadingMediaLength];
			    int byteRead = 0;
			    int totalBytesRead = 0;
			    while (totalBytesRead < downloadingMediaLength) {
			        byteRead = stream.read(dataBytes, totalBytesRead, downloadingMediaLength);
			        totalBytesRead += byteRead;
			    }
				
				FileOutputStream out = new FileOutputStream(file);
				out.write(dataBytes, 0, downloadingMediaLength);
				out.flush();
				out.close();
				
				client.getConnectionManager().shutdown();
				
				play = MediaPlayer.create(context, Uri.fromFile(file));
				play.start();
				loading = false;
			}
		
		} catch (Exception e) {}
	}

	@Override
	public void close() {
		if(play != null) {
			if(play.isPlaying()) {
				play.stop();
			}
		}
	}
	
	@Override
	public void stopSpeaking(){
		play.stop();
	}

	public boolean isSpeakingNow(){
		System.out.println(loading+" "+play.isPlaying());
		if(loading)
			return true;
		else
			return play.isPlaying();
	}
}
